﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Disco.Ontology
{
    public static class DbContextExtensions
    {
        public static void RemoveWithCascadeDelete(this DbContext context, object entity)
        {
            var type = entity.GetType();

            var propertyInfos = type.GetProperties().
                Where(property => IsPropertyForCascadeDelete(property));

            foreach (var property in propertyInfos)
            {
                var dbSet = context.Set(property.PropertyType);
                var value = property.GetValue(entity);
                dbSet.Remove(value);
            }

            var modelSet = context.Set(entity.GetType());
            modelSet.Remove(entity);
        }

        private static IList<string> _typesForCascadeDelete =
            new List<string> { typeof(Descriptor).Name, typeof(Content).Name };

        private static bool IsPropertyForCascadeDelete(PropertyInfo property)
        {
            // HACK: The navigation property types that should be deleted are currently hard coded!
            // TODO: As a Developer I want to configure navigation properties for cascade delete so that I have more flexibility and control over deletion of dependent navigation ends.
            return _typesForCascadeDelete.Contains(property.PropertyType.Name);
        }
    }
}
